#pragma once

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include "Log.hpp"
#include"InetAddr.hpp"


using namespace LogMudule;

class UdpCilent
{
public:
    UdpCilent(std::string ip, uint16_t prot)
        : _ip(ip),
          _prot(prot),
          _addr(prot,ip)
    {
    }

    // 初始化客户端
    void InitClient()
    {
        // 1.创建socket文件描述符
        _socketfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            LOG(LogLevel::ERROR) << "socket error...";
        }

        LOG(LogLevel::DEBUG) << "socket:" << _socketfd;
    }

    // 开始
    void Start()
    {
        LOG(LogLevel::DEBUG) << "启动服务器";
        while (true)
        {
            // 1.发送数据
            std::cout << "Please Enter# ";
            std::string message;
            std::getline(std::cin, message);
            // struct sockaddr_in server_addr;
            // ::bzero(&server_addr, sizeof(server_addr));
            // server_addr.sin_port = ::htons(_prot);
            // server_addr.sin_family = AF_INET;
            // server_addr.sin_addr.s_addr = inet_addr(_ip.c_str());

            int n = ::sendto(_socketfd, message.c_str(), message.size(), 0, _addr.GetAddr(), _addr.Addr_size());
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "sendto error...";
            }
            LOG(LogLevel::DEBUG) << "发送的数据：" << message;

            // 2.接收数据
            struct sockaddr_in temp;
            socklen_t len = sizeof(temp);
            char buffer[1024];
            n = ::recvfrom(_socketfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
            if(n < 0)
            {
                LOG(LogLevel::ERROR) << "recvfrom error...";
            }
            buffer[n] = 0;

            LOG(LogLevel::DEBUG) << "收到的数据：" << buffer;
        }
    }

    ~UdpCilent()
    {
        int n = ::close(_socketfd);
        (void)n;
    }

private:
    uint16_t _prot;  // 端口号
    std::string _ip; // ip地址
    int _socketfd;   // 文件描述符
    InetAddr _addr;
};
